<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>小区物业管理系统 - 登录</title>
    <!-- Tailwind CSS v3 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 统一的 Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4CAF50',
                        secondary: '#8BC34A',
                        background: '#E8F5E9'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
        }
    </style>
</head>
<body class="bg-background min-h-screen flex items-center justify-center p-4">
    <div class="w-full max-w-md">
        <!-- 登录卡片 -->
        <div class="bg-white rounded-lg shadow-lg overflow-hidden">
            <!-- 登录表单 -->
            <div class="p-8">
                <h1 class="text-2xl font-bold text-center mb-6">小区物业管理系统</h1>
                
                <form id="loginForm" class="space-y-4">
                    <div>
                        <input type="text" id="username" name="username" 
                               class="w-full px-4 py-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" 
                               placeholder="admin" value="admin">
                    </div>
                    
                    <div>
                        <input type="password" id="password" name="password" 
                               class="w-full px-4 py-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" 
                               placeholder="••••••••" value="admin">
                    </div>
                    
                    <!-- 登录类型选择 -->
                    <div class="space-y-3 mt-4">
                        <div class="flex items-center">
                            <input type="radio" id="admin" name="userType" value="admin" 
                                   class="h-5 w-5 text-primary focus:ring-primary border-gray-300" checked>
                            <label for="admin" class="ml-2 text-gray-700">管理员</label>
                        </div>
                        <div class="flex items-center">
                            <input type="radio" id="resident" name="userType" value="resident" 
                                   class="h-5 w-5 text-primary focus:ring-primary border-gray-300">
                            <label for="resident" class="ml-2 text-gray-700">居民</label>
                        </div>
                        <div class="flex items-center">
                            <input type="radio" id="employee" name="userType" value="employee" 
                                   class="h-5 w-5 text-primary focus:ring-primary border-gray-300">
                            <label for="employee" class="ml-2 text-gray-700">员工</label>
                        </div>
                    </div>
                    
                    <div class="mt-8">
                        <button type="submit" class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-3 px-4 rounded-md transition-all">
                            登录
                        </button>
                    </div>
                </form>
                
                <!-- 注册链接 -->
                <div class="mt-6 text-center">
                    <a href="#" id="registerButton" class="text-primary hover:text-primary/80">
                        没有账号？去注册
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- 注册模态框 -->
    <div id="registerModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-lg shadow-xl w-full max-w-md mx-4 overflow-hidden">
            <!-- 模态框头部 -->
            <div class="bg-primary p-4 flex justify-between items-center">
                <h3 class="text-lg font-bold text-white">用户注册</h3>
                <button id="closeRegisterModal" class="text-white hover:text-white/80">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            
            <!-- 注册表单 -->
            <div class="p-6">
                <form id="registerForm" class="space-y-4">
                    <div>
                        <label for="regUsername" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                        <input type="text" id="regUsername" name="regUsername" 
                               class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" 
                               placeholder="请输入用户名" required>
                    </div>
                    
                    <div>
                        <label for="regPassword" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                        <input type="password" id="regPassword" name="regPassword" 
                               class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" 
                               placeholder="请输入密码" required>
                    </div>
                    
                    <div>
                        <label for="regConfirmPassword" class="block text-sm font-medium text-gray-700 mb-1">确认密码</label>
                        <input type="password" id="regConfirmPassword" name="regConfirmPassword" 
                               class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" 
                               placeholder="请再次输入密码" required>
                    </div>
                    
                    <!-- 注册类型选择 -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">注册类型</label>
                        <div class="space-y-2">
                            <div class="flex items-center">
                                <input type="radio" id="regResident" name="regUserType" value="resident" 
                                       class="h-4 w-4 text-primary focus:ring-primary border-gray-300" checked>
                                <label for="regResident" class="ml-2 block text-sm text-gray-700">居民</label>
                            </div>
                            <div class="flex items-center">
                                <input type="radio" id="regEmployee" name="regUserType" value="employee" 
                                       class="h-4 w-4 text-primary focus:ring-primary border-gray-300">
                                <label for="regEmployee" class="ml-2 block text-sm text-gray-700">员工</label>
                            </div>
                        </div>
                        <p class="text-xs text-gray-500 mt-1">管理员账号需联系管理员创建</p>
                    </div>
                    
                    <div class="pt-2">
                        <button type="submit" class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-2 px-4 rounded-md transition-all">
                            注册
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // 登录表单提交逻辑
        document.getElementById('loginForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const userType = document.querySelector('input[name="userType"]:checked').value;
            
            // 显示加载状态
            const loginButton = this.querySelector('button[type="submit"]');
            const originalText = loginButton.textContent;
            loginButton.disabled = true;
            loginButton.textContent = '登录中...';
            
            // 调用后端登录API
            fetch('http://localhost:5001/api/auth/login/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                credentials: 'include',
                body: JSON.stringify({ username, password, userType })
            })
            .then(response => {
                // 恢复按钮状态
                loginButton.disabled = false;
                loginButton.textContent = originalText;
                
                if (!response.ok) {
                    // 尝试直接通过SQLite验证（模拟后端验证）
                    return validateUserLocally(username, password, userType);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    console.log('登录成功:', data);
                    // 根据用户类型跳转到不同页面
                    if (userType === 'admin') {
                        window.location.href = 'dashboard.html';
                    } else if (userType === 'resident') {
                        window.location.href = 'index.html';
                    } else if (userType === 'employee') {
                        window.location.href = 'employee/index.html';
                    }
                } else {
                    throw new Error(data.message || '登录失败');
                }
            })
            .catch(error => {
                console.error('登录错误:', error);
                alert(error.message || '登录失败，请检查用户名、密码和用户类型');
            });
        });
        
        // 本地用户验证函数（模拟后端验证）
        function validateUserLocally(username, password, userType) {
            return new Promise((resolve, reject) => {
                // 这里模拟数据库验证逻辑，基于property_user表结构
                // 在实际应用中，这部分应该由后端处理
                const users = {
                    // 基于property_user表的用户数据
                    'root': { password: '123456', user_type: '管理员' },
                    'user': { password: '123456', user_type: '普通用户' },
                    'zzzz': { password: '123456', user_type: 'employee' },
                    // 可以添加更多预设账号
                };
                
                // 检查用户是否存在
                const user = users[username];
                if (!user) {
                    reject({ success: false, message: '用户不存在' });
                    return;
                }
                
                // 验证密码
                if (user.password !== password) {
                    reject({ success: false, message: '密码错误' });
                    return;
                }
                
                // 验证用户类型匹配
                if (userType === 'admin' && user.user_type !== '管理员') {
                    reject({ success: false, message: '该账号不是管理员账号' });
                    return;
                }
                
                if (userType === 'resident' && user.user_type !== '普通用户') {
                    reject({ success: false, message: '该账号不是居民账号' });
                    return;
                }
                
                if (userType === 'employee' && user.user_type !== 'employee') {
                    reject({ success: false, message: '该账号不是员工账号' });
                    return;
                }
                
                // 验证通过
                resolve({ success: true, user: { username, userType } });
            });
        }
        
        // 注册模态框相关逻辑
        const registerButton = document.getElementById('registerButton');
        const registerModal = document.getElementById('registerModal');
        const closeRegisterModal = document.getElementById('closeRegisterModal');
        const registerForm = document.getElementById('registerForm');
        
        // 显示注册模态框
        registerButton.addEventListener('click', function() {
            registerModal.classList.remove('hidden');
        });
        
        // 关闭注册模态框
        closeRegisterModal.addEventListener('click', function() {
            registerModal.classList.add('hidden');
        });
        
        // 点击模态框背景关闭
        registerModal.addEventListener('click', function(e) {
            if (e.target === registerModal) {
                registerModal.classList.add('hidden');
            }
        });
        
        // 注册表单提交
        registerForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const username = document.getElementById('regUsername').value;
            const password = document.getElementById('regPassword').value;
            const confirmPassword = document.getElementById('regConfirmPassword').value;
            const userType = document.querySelector('input[name="regUserType"]:checked').value;
            
            // 表单验证
            if (!username || !password) {
                alert('请输入用户名和密码');
                return;
            }
            
            if (password !== confirmPassword) {
                alert('两次输入的密码不一致');
                return;
            }
            
            if (password.length < 6) {
                alert('密码长度至少为6位');
                return;
            }
            
            // 显示加载状态
            const registerSubmitButton = this.querySelector('button[type="submit"]');
            const originalText = registerSubmitButton.textContent;
            registerSubmitButton.disabled = true;
            registerSubmitButton.textContent = '注册中...';
            
            // 调用后端注册API
            fetch('http://localhost:5001/api/auth/register/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                credentials: 'include',
                body: JSON.stringify({ username, password, userType })
            })
            .then(response => {
                // 恢复按钮状态
                registerSubmitButton.disabled = false;
                registerSubmitButton.textContent = originalText;
                
                if (!response.ok) {
                    return response.json().then(errorData => {
                        throw new Error(errorData.error || '注册失败');
                    }).catch(() => {
                        throw new Error('注册失败，请检查网络连接');
                    });
                }
                return response.json();
            })
            .then(data => {
                console.log('注册成功:', data);
                alert('注册成功，请登录');
                // 关闭模态框
                registerModal.classList.add('hidden');
                // 可以自动填充用户名到登录表单
                document.getElementById('username').value = username;
                document.getElementById('password').focus();
            })
            .catch(error => {
                console.error('注册错误:', error);
                alert(error.message || '注册失败，请稍后重试');
            });
        });
        
        // 模态框按ESC键关闭
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && !registerModal.classList.contains('hidden')) {
                registerModal.classList.add('hidden');
            }
        });
    </script>
</body>
</html>